/*
 * Copyright (c) 2012, Codename One. All rights reserved.
 */
package com.codename1.designer;

import java.awt.Desktop;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.prefs.Preferences;
import javax.swing.JOptionPane;
import javax.swing.ProgressMonitor;
import javax.swing.SwingUtilities;

/**
 *
 * @author Shai Almog
 */
public class LoginDialog extends javax.swing.JDialog {
    private boolean initialized;
    private static String globalUser;
    private static String globalPassword;

    /** Creates new form LoginDialog */
    public LoginDialog(java.awt.Component parent) {
        super((java.awt.Frame)SwingUtilities.getWindowAncestor(parent), true);
        initComponents();
        ModifiableJOptionPane.reverseOKCancel(loginButton, cancelButton);
        Preferences p = Preferences.userNodeForPackage(getClass());
        remember.setSelected(p.getBoolean("remeber", false));
        if(remember.isSelected()) {
            user.setText(p.get("user", ""));
            password.setText(p.get("pass", ""));
            globalUser = user.getText();
            globalPassword = user.getText();
        }
        initialized = true;
        setLocationByPlatform(true);
        pack();
        setVisible(true);
    }

    public static String getUser(java.awt.Component parent) {
        initUserPassword(parent);
        return globalUser;
    }
    
    public static String getPassword(java.awt.Component parent) {
        initUserPassword(parent);
        return globalPassword;
    }
    
    private static void initUserPassword(java.awt.Component parent) {
        if(globalUser == null) {
            Preferences p = Preferences.userNodeForPackage(LoginDialog.class);
            if(p.getBoolean("remeber", false)) {
                globalUser = p.get("user", "");
                globalPassword = p.get("pass", "");
            } else {
                new LoginDialog(parent);
            }
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        signup = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        user = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        password = new javax.swing.JPasswordField();
        jLabel5 = new javax.swing.JLabel();
        remember = new javax.swing.JCheckBox();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        loginButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        FormListener formListener = new FormListener();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Login To Codename One");
        setModal(true);

        jPanel3.setName("jPanel3"); // NOI18N

        signup.setText("Signup for a full account at codenameone.com");
        signup.setName("signup"); // NOI18N
        signup.addActionListener(formListener);
        jPanel3.add(signup);

        jLabel3.setText("Username");
        jLabel3.setName("jLabel3"); // NOI18N

        user.setName("user"); // NOI18N

        jLabel4.setText("Password");
        jLabel4.setName("jLabel4"); // NOI18N

        password.setName("password"); // NOI18N

        jLabel5.setText("Remember Password");
        jLabel5.setName("jLabel5"); // NOI18N

        remember.setName("remember"); // NOI18N
        remember.addActionListener(formListener);

        jPanel1.setName("jPanel1"); // NOI18N

        jPanel2.setName("jPanel2"); // NOI18N
        jPanel2.setLayout(new java.awt.GridLayout());

        loginButton.setText("Login");
        loginButton.setName("loginButton"); // NOI18N
        loginButton.addActionListener(formListener);
        jPanel2.add(loginButton);

        cancelButton.setText("Cancel");
        cancelButton.setName("cancelButton"); // NOI18N
        cancelButton.addActionListener(formListener);
        jPanel2.add(cancelButton);

        jPanel1.add(jPanel2);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 414, Short.MAX_VALUE)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 411, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel4)
                            .add(jLabel3)
                            .add(jLabel5))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(remember)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 224, Short.MAX_VALUE))
                            .add(user, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE)
                            .add(password, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE))))
                .add(3, 3, 3))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(user, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(password, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel5)
                    .add(remember))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == signup) {
                LoginDialog.this.signupActionPerformed(evt);
            }
            else if (evt.getSource() == remember) {
                LoginDialog.this.rememberActionPerformed(evt);
            }
            else if (evt.getSource() == loginButton) {
                LoginDialog.this.loginButtonActionPerformed(evt);
            }
            else if (evt.getSource() == cancelButton) {
                LoginDialog.this.cancelButtonActionPerformed(evt);
            }
        }
    }// </editor-fold>//GEN-END:initComponents

private void signupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_signupActionPerformed
        try {
            Desktop.getDesktop().browse(new URI("http://www.codenameone.com/gui"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
}//GEN-LAST:event_signupActionPerformed

private void rememberActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rememberActionPerformed
        if(initialized) {
            Preferences p = Preferences.userNodeForPackage(getClass());
            p.putBoolean("remeber", remember.isSelected());
        }
}//GEN-LAST:event_rememberActionPerformed

private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed
    signup.setEnabled(false);
    loginButton.setEnabled(false);
    user.setEnabled(false);
    password.setEnabled(false);
    final ProgressMonitor mon = new ProgressMonitor(this, "Logging In", "Connecting To Server", 0, 100);
    mon.setMillisToDecideToPopup(0);
    mon.setProgress(1);
    new Thread() {
        public void run() {
            try {
                mon.setProgress(40);
                URL u = new URL("https://codename-one.appspot.com/getData?m=login&u=" + URLEncoder.encode(user.getText(), "UTF-8") + 
                        "&p=" + URLEncoder.encode(password.getText(), "UTF-8"));
                InputStream i = u.openStream();
                byte[] b = new byte[4];
                i.read(b);
                i.close();
                mon.setProgress(90);
                
                // success
                if(b[0] == 'O') {
                    Preferences p = Preferences.userNodeForPackage(getClass());
                    if(remember.isSelected()) {
                        p.put("user", user.getText());
                        p.put("pass", password.getText());
                    } else {
                        p.remove("user");
                        p.remove("pass");
                    }
                    globalPassword = password.getText();
                    globalUser = user.getText();

                    dispose();            
                } else {
                    signup.setEnabled(true);
                    loginButton.setEnabled(true);
                    user.setEnabled(true);
                    password.setEnabled(true);
                    
                    // fail
                    if(b[0] == 'F') {
                        signup.setText("Login Failed, check user/password");
                    } else {
                        // unknown error maybe proxy
                        JOptionPane.showMessageDialog(LoginDialog.this, "Login Failed", "Unable to connect, check proxy settings", JOptionPane.ERROR_MESSAGE);
                    }
                }
                mon.close();
            } catch (Exception ex) {
                ex.printStackTrace();
                signup.setEnabled(true);
                loginButton.setEnabled(true);
                user.setEnabled(true);
                password.setEnabled(true);
                JOptionPane.showMessageDialog(LoginDialog.this, "Login Failed", "Internal Error:\n" + ex, JOptionPane.ERROR_MESSAGE);
            }            
        }
    }.start();

}//GEN-LAST:event_loginButtonActionPerformed

private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
    dispose();
}//GEN-LAST:event_cancelButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JButton loginButton;
    private javax.swing.JPasswordField password;
    private javax.swing.JCheckBox remember;
    private javax.swing.JButton signup;
    private javax.swing.JTextField user;
    // End of variables declaration//GEN-END:variables
}
